package com.w3coffee.web.oauth.qqweibo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import net.javawind.t_api.beans.OAuth;
import net.javawind.t_api.commons.User_API;
import net.javawind.t_api.utils.OAuthClient;

import com.w3coffee.web.User;
import com.w3coffee.web.control.CheckinToken;
import com.w3coffee.web.oauth.IOauthApi;

public class QQWeiboOauthApiImpl implements IOauthApi {
	private QQWeiboConfig config;

	public QQWeiboConfig getConfig() {
		return config;
	}

	public void setConfig(QQWeiboConfig config) {
		this.config = config;
	}
	
	@Override
	public void oauthRequest(HttpServletRequest req, HttpServletResponse resp, String backUrl) throws Exception {
		OAuth oauth = new OAuth(config.getAppKey(), config.getAppSecret(), backUrl); // 初始化OAuth请求令牌
		OAuthClient auth = new OAuthClient();// OAuth 认证对象

		oauth = auth.requestToken(oauth);
		CheckinToken ct = (CheckinToken) req.getSession(false).getAttribute("TOKEN");
		User user = ct.getUser();
		user.setAuthAgent(oauth);
		user.setRequestToken(auth);
		String authUrl = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="
					+ oauth.getOauth_token();
		resp.sendRedirect(authUrl);
	}

	@Override
	public void doAuth(User user) throws Exception {
		OAuth oauth = (OAuth) user.getAuthAgent();
		OAuthClient auth = (OAuthClient) user.getRequestToken();
		oauth.setOauth_verifier(user.getVerifier());
		oauth = auth.accessToken(oauth);
		
		User_API uapi = new User_API();
		String jsonData = uapi.info(oauth, "json");
		JSONObject jo = new JSONObject(jsonData);
		JSONObject data = (JSONObject) jo.get("data");
		user.setId(data.getString("name"));
		user.setName(data.getString("nick"));
		user.setHeadUrl(data.getString("head"));
		user.setFansNum(data.getInt("fansnum"));
		user.setIntro(data.getString("introduction"));
		user.setVip(data.getInt("isvip") != 0);
	}
}
